/*
 * Created by kopper on 13.02.15 17:26
 * (C) Copyright 2015 kopperek@gmail.com
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 */

package app.android.kopper.foramemo.util;

import android.content.ContentValues;
import android.os.Environment;
import android.util.Xml;

import org.xmlpull.v1.XmlSerializer;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Set;

public class ExportUtil {

    public static File performExport(ForaMemoDbHelper dbHelper,String fileNameSuffix) throws IOException {
        Set<Word> words=dbHelper.selectWords(dbHelper.getReadableDatabase(),null,null,null);
        if(words.size()>0) {
            File storageDirectory=Environment.getExternalStorageDirectory();
            File foraMemoDir=createDirectory(storageDirectory,"ForaMemo");
            String fileName=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+fileNameSuffix+".xml";
            File xmlFile=new File(foraMemoDir,fileName);
            XmlSerializer serializer = Xml.newSerializer();
            FileOutputStream fos=new FileOutputStream(xmlFile);
            serializer.setOutput(fos,"UTF-8");
            serializer.startDocument("UTF-8",true);
            for(Word word:words) {
                serializer.startTag(null,ForaMemoDbHelper.FeedEntry.TABLE_NAME);
                ContentValues values=word.createValues();
                for(Map.Entry<String,Object> key:values.valueSet())
                    serializer.attribute(null,key.getKey(),String.valueOf(key.getValue()));
                serializer.endTag(null,ForaMemoDbHelper.FeedEntry.TABLE_NAME);
            }
            serializer.endDocument();
            serializer.flush();
            fos.flush();
            fos.close();
            return(xmlFile);
        }
        return null;
    }

    private static File createDirectory(File parent,String name) throws IOException {
        File file=new File(parent,name);
        LogProxy.i(file.getAbsolutePath());
        if(!file.exists()) {
            if(!file.mkdir())
                throw new IOException("Directory not created ("+name+")");
        } else {
            if(!file.isDirectory())
                throw new IOException("Not directory  ("+name+")");
        }
        return(file);
    }
}
